import { useState, useEffect, useContext } from 'react';
import { NavBar, SearchBar, List, InfiniteScroll } from "antd-mobile";
import { useHistory, useRouteMatch } from 'react-router-dom';
import xss from 'xss';
import moment from 'moment';

import FileIcon from '../../../components/FileIcon';

import { transferFileSize } from '../../../utils';
import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [result, setResult] = useState([]);
  const { params: { cid } } = useRouteMatch();
  const [pagination, setPagination] = useState({ pageIndex: 1 });

  // 处理”搜索“事件
  const handleSearch = async (pageIndex = 1, searchKey = undefined) => {
    const { rows, current, totalItemCount, totalPage } = await mySdkStore.sdk.searchMessage({ searchKey, resourceType: 'file', pageIndex, sessionIds: [cid] });
    setResult(pageIndex === 1 ? rows : [...result, ...rows]);

    setPagination({ pageIndex: current, totalItemCount, totalPage })
  }

  // 处理分页获取数据
  const getNextData = async () => {
    await handleSearch(pagination.pageIndex + 1);
  }

  useEffect(() => {
    handleSearch(1);
  }, []);

  return (
    <div className="searchMessageFilePage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>文件</NavBar>
      <div className="searchBar">
        <SearchBar placeholder='搜索' className="searchInput" style={{ margin: 12, '--background': '#fff' }} onSearch={val => handleSearch(1, val)} />
      </div>
      <List>
        { result.map((item => {
          return <List.Item
            key={item.msgId}
            prefix={<FileIcon type={item.msgContent?.type} />}
            description={<>{transferFileSize(item.msgContent?.size)} {item.from?.nickName} { moment(item.timestamp).format('YYYY-MM-DD HH:mm') } 创建</>}
          >
            <div className="searchContent" dangerouslySetInnerHTML={{__html: xss(item.searchContent)}}></div>
          </List.Item>
        })) }
      </List>
      <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
    </div>)
}